package com.i2works.smartluolong.web.service.merchant.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.i2works.smartluolong.utils.base.FlowConstant;
import com.i2works.smartluolong.utils.base.FlowItemTypeEnum;
import com.i2works.smartluolong.utils.base.GlobalConstant;
import com.i2works.smartluolong.utils.base.MerchantStatusEnum;
import com.i2works.smartluolong.utils.basecommon.BaseCommonServiceImpl;
import com.i2works.smartluolong.utils.exception.DAOException;
import com.i2works.smartluolong.utils.exception.ServiceException;
import com.i2works.smartluolong.web.dal.merchant.dao.IMerchantApplyDAO;
import com.i2works.smartluolong.web.entity.cart.CartReceiveDO;
import com.i2works.smartluolong.web.entity.flow.FlowInfoDO;
import com.i2works.smartluolong.web.entity.flow.FlowInfoQuery;
import com.i2works.smartluolong.web.entity.flow.FlowProcessDO;
import com.i2works.smartluolong.web.entity.merchant.*;
import com.i2works.smartluolong.web.service.cart.ICartReceiveService;
import com.i2works.smartluolong.web.service.flow.IFlowInfoService;
import com.i2works.smartluolong.web.service.flow.IFlowProcessService;
import com.i2works.smartluolong.web.service.merchant.IMerchantApplyImagesService;
import com.i2works.smartluolong.web.service.merchant.IMerchantApplyMemberService;
import com.i2works.smartluolong.web.service.merchant.IMerchantApplyService;
import com.xiaoleilu.hutool.util.CollectionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

/**
 * 个体商户申请 - 业务层接口
 *
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/7/23 21:09
 */
@Service("merchantApplyService")
public class MerchantApplyServiceImpl extends BaseCommonServiceImpl<MerchantApplyQuery, MerchantApplyDO> implements IMerchantApplyService {

    private final IMerchantApplyDAO merchantApplyDAO;
    private final IMerchantApplyImagesService merchantApplyImagesService;
    private final IMerchantApplyMemberService merchantApplyMemberService;
    private final IFlowInfoService flowInfoService;
    private final IFlowProcessService flowProcessService;
    private final ICartReceiveService cartReceiveService;

    @Autowired
    public MerchantApplyServiceImpl(IMerchantApplyDAO merchantApplyDAO, IMerchantApplyImagesService merchantApplyImagesService, IMerchantApplyMemberService merchantApplyMemberService, IFlowInfoService flowInfoService, IFlowProcessService flowProcessService, ICartReceiveService cartReceiveService) {
        this.merchantApplyDAO = merchantApplyDAO;
        this.merchantApplyImagesService = merchantApplyImagesService;
        this.merchantApplyMemberService = merchantApplyMemberService;
        this.flowInfoService = flowInfoService;
        this.flowProcessService = flowProcessService;
        this.cartReceiveService = cartReceiveService;
    }



    /**
     * 添加工商申请
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void saveOrUpdate(MerchantApplyDO merchantApplyDO) throws ServiceException {
        String flowInfoMessage;
        try {
            if (merchantApplyDO.getId() != null) {
                merchantApplyDAO.update(merchantApplyDO);
                flowInfoMessage = "用户《" + merchantApplyDO.getUpdateName() + "》重提申请";
            } else {
                merchantApplyDO.setCreateName(merchantApplyDO.getUpdateName());
                merchantApplyDAO.save(merchantApplyDO);
                flowInfoMessage = "用户《" + merchantApplyDO.getUpdateName() + "》新增申请";
            }
            //证照处理
            List<String> imagesList = merchantApplyDO.getMerchantImagesList();
            if (CollectionUtil.isNotEmpty(imagesList)) {
                //删除图片
                merchantApplyImagesService.delete(merchantApplyDO.getId());
                //添加图片
                for (String images : imagesList) {
                    MerchantApplyImagesDO imagesDO = new MerchantApplyImagesDO();
                    imagesDO.setApplyId(merchantApplyDO.getId());
                    imagesDO.setImg(images);
                    imagesDO.setUpdateName(merchantApplyDO.getUpdateName());
                    imagesDO.setCreateName(merchantApplyDO.getCreateName());
                    merchantApplyImagesService.save(imagesDO);
                }
            }
            //添加工作流
            FlowInfoDO flowInfoDO = new FlowInfoDO();
            flowInfoDO.setUserId(merchantApplyDO.getUserId());
            flowInfoDO.setItemStatus(MerchantStatusEnum.STATUS_0.getKey());
            flowInfoDO.setItemId(merchantApplyDO.getId());
            flowInfoDO.setComplete(0);
            flowInfoDO.setItemName(merchantApplyDO.getMerchantName() + "-" + FlowItemTypeEnum.MERCHANT_APPLY.getValue());
            flowInfoDO.setItemType(FlowItemTypeEnum.MERCHANT_APPLY.getKey());
            flowInfoDO.setMessage(flowInfoMessage);
            flowInfoDO.setUpdateName(merchantApplyDO.getUpdateName());
            flowInfoDO.setCreateName(merchantApplyDO.getCreateName());
            flowInfoService.save(flowInfoDO);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }
    
    
    /**
     * 获取审核人员可管理的申请列表
     */
    @Override
    public List<MerchantApplyDO> queryListByAuditor(MerchantApplyQuery query) throws ServiceException {
        try {
            return merchantApplyDAO.queryListByAuditor(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 获取审核人员可管理的申请列表统计
     */
    @Override
    public Integer queryCountByAuditor(MerchantApplyQuery query) throws ServiceException {
        try {
            return merchantApplyDAO.queryCountByAuditor(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 获取申请资料详情
     */
    @Override
    public Map<String, Object> getApplyDetail(Integer applyId) throws ServiceException {
        Map<String, Object> map = Maps.newHashMap();
        try {
            //查询详情
            MerchantApplyQuery applyQuery = new MerchantApplyQuery();
            applyQuery.setId(applyId);
            MerchantApplyDO merchantApply = merchantApplyDAO.query(applyQuery);
            if (null != merchantApply) {
                map.put("merchantApply", merchantApply);
                String[] merchantBrandOptionalList = StringUtils.split(merchantApply.getMerchantBrandOptional(), ",");
                map.put("merchantBrandOptionalList", merchantBrandOptionalList);
                //查询经营者个人信息
                MerchantApplyMemberQuery memberQuery = new MerchantApplyMemberQuery();
                memberQuery.setApplyId(merchantApply.getId());
                memberQuery.setStatus(GlobalConstant.status.TRUE);
                MerchantApplyMemberDO merchantApplyMemberDO = merchantApplyMemberService.query(memberQuery);
                map.put("member", merchantApplyMemberDO);
                //查询资料图片
                MerchantApplyImagesQuery imagesQuery = new MerchantApplyImagesQuery();
                imagesQuery.setApplyId(merchantApply.getId());
                List<MerchantApplyImagesDO> imagesList = merchantApplyImagesService.queryList(imagesQuery);
                map.put("imagesList", imagesList);
            }
        } catch (DAOException e) {
         throw new ServiceException(e);
        }
        return map;
    }


    /**
     * 更新申请状态
     *
     * @param merchantApplyDO 申请实体
     * @param auditorId       审核人员ID
     * @param isClaim         是否认领状态
     */
    @Override
    @Transactional(rollbackFor = ServiceException.class)
    public void updateApplyStatus(MerchantApplyDO merchantApplyDO, Integer auditorId, Boolean isClaim) throws ServiceException {
        try {
            //更新申请表
            merchantApplyDAO.update(merchantApplyDO);
            //新增流程记录
            FlowInfoQuery infoQuery = new FlowInfoQuery();
            infoQuery.setItemId(merchantApplyDO.getId());
            infoQuery.setItemType(FlowItemTypeEnum.MERCHANT_APPLY.getKey());
            FlowInfoDO infoDO = flowInfoService.query(infoQuery);
            infoDO.setItemStatus(merchantApplyDO.getApplyStatus());
            //如果是认领（待审核），就设置审核人ID为空(-1，mybatis自行处理)
            if (isClaim) {
                infoDO.setAuditorId(FlowConstant.base.NULL);
            } else {
                infoDO.setAuditorId(auditorId);
            }
            //如果状态是4（核准通过），设置状态为已完成
            if (merchantApplyDO.getApplyStatus().equals(MerchantStatusEnum.STATUS_4.getKey())) {
                infoDO.setComplete(FlowConstant.complete.TRUE);
                //添加签发认领表信息
                CartReceiveDO cartReceiveDO = new CartReceiveDO();
                cartReceiveDO.setItemId(merchantApplyDO.getId());
                cartReceiveDO.setItemName(merchantApplyDO.getMerchantName());
                cartReceiveDO.setItemUserId(merchantApplyDO.getUserId());
                cartReceiveDO.setItemType(FlowItemTypeEnum.MERCHANT_APPLY.getKey());
                cartReceiveDO.setStatus(GlobalConstant.status.TRUE);
                cartReceiveDO.setUpdateName(merchantApplyDO.getUpdateName());
                cartReceiveDO.setCreateName(merchantApplyDO.getUpdateName());
                cartReceiveService.save(cartReceiveDO);
            }
            infoDO.setUpdateName(merchantApplyDO.getUpdateName());
            infoDO.setUpdateTime(merchantApplyDO.getUpdateTime());
            flowInfoService.update(infoDO);
            //插入记录表
            FlowProcessDO flowProcessDO = new FlowProcessDO();
            flowProcessDO.setAuditorId(auditorId);
            flowProcessDO.setItemId(merchantApplyDO.getId());
            flowProcessDO.setItemType(FlowItemTypeEnum.MERCHANT_APPLY.getKey());
            //洛阳市洛龙区花都小吃店 - 个体工商营业执照申请
            flowProcessDO.setItemTitle(merchantApplyDO.getMerchantName() + "-" + FlowItemTypeEnum.MERCHANT_APPLY.getValue());
            flowProcessDO.setMessage(merchantApplyDO.getAuditMessage());
            flowProcessDO.setAuditStatus(merchantApplyDO.getApplyStatus());
            flowProcessDO.setUpdateName(merchantApplyDO.getUpdateName());
            flowProcessDO.setCreateName(merchantApplyDO.getUpdateName());
            flowProcessService.save(flowProcessDO);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }

    /**
     * 查询报表列表
     */
    @Override
    public List<JSONObject> queryReportList(MerchantApplyQuery query) throws ServiceException {
        try {
            return merchantApplyDAO.queryReportList(query);
        } catch (DAOException e) {
            throw new ServiceException(e);
        }
    }
}
